<?php
/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi

    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/
/**
 * 
 * @author colin
 *
 */

class professorsActions extends sfActions{
  public function executeEdit(sfWebRequest $request)
  {
  	$uid = $this->getUser()->getId();
  	$this->prof = ProfPeer::retrieveByUserId($uid);
  	$this->prof_form = new ProfForm($this->prof);
  	$this->course_admins = CourseAdminPeer::retrieveByProfId($this->prof->getId(),true);
  	$this->course_admins = $this->uniqueByEmail($this->course_admins);
  	echo print_r($this->course_admins);
  }
  
  public function executeCreate(sfWebRequest $request){
  	    $this->forward404Unless($request->isMethod(sfRequest::POST));
  		$user_info = $request->getParameter("user");
  		$course_name = $request->getParameter("course_name");
  		if(!$course_name)
  			$course_name = "your courses";
  		$prof_email = $user_info["email"];
  		$c = new Criteria();
  		$c->add(CoursePeer::INSTRUCTOR_EMAIL, $prof_email);
  		$courses = CoursePeer::doSelect($c);
  		if(!$courses || count($courses) == 0 ){
  			$this->setTemplate("noauth","professors");
  			return;
  		}

  	    $user = new User();
	    $this->user_form = new UserForm($user);
	    // set a month and day for the birthdate to jan 1 since users only require their birth year
	    $user_info['birthdate']['month'] = "1";
	    $user_info['birthdate']['day'] = "1";
	    echo print_r($user_info);
	    $this->user_form->bind($user_info, array());
		$error = false;
	    // make sure the network they pick matches the domain email for Harvard
		if(UserPeer::$networks[$user_info['network_id']] == 'Harvard' && trim(substr($user_info['email'], -11)) != 'harvard.edu') {
			$this->getUser()->setFlash('error', "You're email address must belong to the harvard.edu domain");
			
			// for testing
			
			//$error = true;
		}
		
	    if(!$error && $this->user_form->isValid()) {
	      $user = $this->user_form->updateObject();

	    
	      $network_id = $user->getNetworkId();
	      if(UserPeer::$networks[$network_id] == 'Other')		// check if the network id corresponds to 'Other' in networks array
	      		$network_name = $this->user_form->getValue('network_name');
	      else
	      		$network_name = $user->getNetworkDisplayName();		
		  $user->setNetworkName($network_name);
	      $user->setMd5Password(md5($this->user_form->getValue('password')));
	      $user->setLanguage('en');
	      $user->setActivated(0);	// this account is new and needs to be activated
	      $user->save();
	      
	      $prof = new Prof();
		  $prof->setUserId($user->getId());
		  $prof->save();
		  //echo "  Prof created+ ".$prof->getId();
		  //make course admins
		  foreach($courses as $course){
		  	$ca = CourseAdminPeer::getProfCourseAdmin($prof->getId(),$user->getId(),$course->getId());
		  	$ca->save();
		  	//echo "  ca created+".$ca->getId();
		  }
		  
	      // add a new a.nnotate server account for this user, this allows document uploading and annotation
	      $annotate_email = $user->getEmail();
	      $annotate_sig = $user->getUsername();
	      $annotate_api = new AnnotateApi();
	      $annotate_api->createAccount($annotate_email, $annotate_sig);

	      // now we need a user activation object for this account
	      $activation = new UserActivation();
	      
    	  $token = substr(md5(time()),4,11);		// our token is the 11 characters after the first four of a md5 hash of the current unix timestamp
		  $activation->setToken($token);			// set the token
		  $activation->setUserId($user->getId());	// set the user_id
		  
		  $activation->save();		// save object to the database
	      
	      // now what we need to do is generate an activation url to email the user      
	      $activation_url = $this->generateUrl('activation', array('id'=>$activation->getId(), 'token'=>$activation->getToken()), true);
	      
	      // retrieve the smtp server from the app.yml
		  $smtp_server = sfConfig::get('app_smtp_server');
		  $smtp_user = sfConfig::get('app_smtp_user');
		  $smtp_password = sfConfig::get('app_smtp_password');
		  try
		  {
		    // Create the mailer
		    $connection = new Swift_Connection_SMTP($smtp_server, 465, Swift_Connection_SMTP::ENC_SSL);
		    $connection->setUsername($smtp_user);
		    $connection->setPassword($smtp_password);
		    $mailer = new Swift($connection);  
		  
		  	// Subject line
		  	$message = new Swift_Message('Welcome to FinalsClub.org');
		 
		  	// Render message parts - do a network check to determine which message
		  //	echo "name: ".$user->getFullName()."<br>course_name: ".$course_name."<br>".$activation_url;
		  	$mailContext = array('name'=>$user->getFullName(), 'url'=>$activation_url, 'course_name'=> $course_name);	// to be passed as parameters to the partials
		  	$message->attach(new Swift_Message_Part($this->getPartial('welcomeToFinalsClubHtml', $mailContext), 'text/html'));		// HTML e-mail body
		  	$message->attach(new Swift_Message_Part($this->getPartial('welcomeToFinalsClubPlain', $mailContext), 'text/plain'));	// Plaintext e-mail body
		 
		  	// Set the 'To' and 'From' fields
		  	$mailer->send($message, $user->getEmail(), $smtp_user);
		  	$mailer->disconnect();
		  }
		  catch (Exception $e)
		  {
		    $this->logMessage($e->getMessage(), 'crit');	// Log the exception as critical
		  	$this->getUser()->setFlash('warning', 'Failed to initialize mailer!');		// alert the user e-mailing failed
		  }
	      
	      if($this->getUser()->hasFlash('invited')) {	// check for the flash variable 'invited' which indicates the user is registering from a invitation link
	      	if($this->getUser()->getFlash('invited')) {
	      		$invitation = InvitationPeer::retrieveByEmail($user->getEmail());	// get invitation object
	      		if($invitation instanceOf Invitation) {		// check for a valid invitation object
	      			$invitation->setRecipientId($user->getId());	// set the recipient_id of the invitation
	      			$invitation->setStatus(InvitationPeer::ACCEPTED);	// set the invitation status to 'ACCEPTED' (2)
	      			$invitation->save();
	      		}
	      	}
	      }
	      $this->getUser()->setFlash('success', 'Your account has been successfully created. A verification email has been sent to your inbox. Please use the activation link in your email to verify your account.');
	      $this->setTemplate("confirm","professors");
	      // Log in the user
	    } else {
		   $this->setTemplate('noauth',"professors");		
		   
		} 	
  }
  
  public function executeUpdate(sfWebRequest $request){
  	$this->forward404unless($request->isMethod("post"));
  	$prof_request = $request->getParameter("prof");
  	$new_admins = $request->getParameter("admins");
  	$prof_request['user_id'] = $this->getUser()->getId();
  	$prof = ProfPeer::retrieveByPK($prof_request['id']);
  	unset($prof_request['id']);
  	$admins = $request->getParameter("admins");
  	$prof_form = new ProfForm($prof);
  	$prof = $prof_form->updateObject($prof_request);
  	$prof->save();
  	
  	
  	//Take care of CourseAdmin stuff
  	
  	$current_admins = CourseAdminPeer::retrieveByProfId($prof->getId(), true);
  	
  	foreach($current_admins as $key => $current_admin){
  		$email = $current_admin->getUser()->getEmail();
  		if(in_array($email,$new_admins)){
  			$this->unsetByValue($new_admins, $email);
  		}else{
  			$current_admin->delete();
  		}
  	}
	
  	//make any new CourseAdmin objects
	$this->makeAuxCourseAdmin($prof, $new_admins);

  	$this->getUser()->setFlash("Success", "Changes Successful");
  	//$this->redirect($request->getReferer());
  }
  
  public function executeNew(sfWebRequest $request){
  		$this->form = new UserForm();

		if($this->getUser()->hasFlash('invited')) {
			if($this->getUser()->hasFlash('email')) {
				$email = $this->getUser()->getFlash('email');
				$this->form->setDefault('user[email]', $email);
			}
			$this->getUser()->setFlash('invited', true);
		}
  }
  
  private function unsetByValue(Array $arr, $val){
  	foreach($arr as $key => $element){
  		if($element === $val)
  			unset($arr[$key]);
  	}
  	return $arr;
  }
  
  private function uniqueByEmail(Array $arr){
  	$redundant = array();
  	$copy = $arr;
  	foreach($copy as $key => $element){
  		if(in_array($element->getUser()->getEmail(),$redundant))
  			unset($arr[$key]);
  		else
  			$redundant[]=$element->getUser()->getEmail();
  	}
  	return array_values($arr);
  }
  
  
	private function makeAuxCourseAdmin(Prof $prof , Array $emails){
		$c = new Criteria();
		$c->add(CoursePeer::INSTRUCTOR_EMAIL, $prof->getUser()->getEmail());
		$courses = CoursePeer::doSelect($c);
		
		foreach($emails as $email){
			//blank entries
			if(trim($email) === "")
				continue;
				
			$user = UserPeer::retrieveByEmail($email);
			
			//user is not yet registered --> make dummy account and send email
			if(!$user){
	// to be passed as parameters to the partials
				$user = SentSpamPeer::getCourseAdminInvite($email,$courses[0],$prof);			    				
			}
				//make course admin objects for all of this professors courses
		
			foreach($courses as $course){
				$ca = new CourseAdmin();
				$ca->setUserId($user->getId());
				$ca->setProfessorId($prof->getId());
				$ca->setCourseId($course->getId());
				$ca->save();
			}
		}
		return;
	}  

}  